package logic

import (
	"context"
	"encoding/json"
	"hippo/hipporpc/hipporpc"
	"hippo/hipporpc/internal/svc"
	"hippo/model/cache"
	"hippo/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type HippoListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHippoListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HippoListLogic {
	return &HippoListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HippoListLogic) HippoList(in *hipporpc.HippoListRequest) (*hipporpc.HippoListResponse, error) {
	// todo: add your logic here and delete this line
	var hippo []mysql.HippoData
	result, _ := cache.Rdb.Get(l.ctx, "HippoList").Result()
	if result == "" {
		mysql.DB.Debug().Model(&mysql.Hippo{}).
			Select("hippos.*, classes.name as class_name").
			Joins("left join classes on classes.id = hippos.class_id").
			Find(&hippo)

		marshal, _ := json.Marshal(&hippo)
		cache.Rdb.Set(l.ctx, "HippoList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &hippo)
	}
	var hippos []*hipporpc.HippoList
	for _, data := range hippo {
		list := hipporpc.HippoList{
			Name:      data.Name,
			Image:     data.Image,
			Price:     float32(data.Price),
			ClassName: "",
			HippoId:   int64(data.ID),
		}
		hippos = append(hippos, &list)
	}

	return &hipporpc.HippoListResponse{
		List: hippos,
	}, nil
}
